package com.example.recorder;


import android.content.Context;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author hdz
 * @date 2019/06/23
 */
public class HomeFragment extends Fragment implements AdapterView.OnItemSelectedListener, AudioPlayer.IAudioPlayCallback {

    private static final String TAG = "HomeFragment";

    private IWorkStateCallback mWorkStateCallback;

    private AudioPlayer mAudioPlayer;
    private AudioRecorder mAudioRecorder;

    private boolean mAudioPlaying = false;
    private boolean mAudioRecording = false;
    private boolean mIsSaveRecord = true;
    private Handler mHandler;

    public HomeFragment() {
        // Required empty public constructor
    }

    public void setCallback(IWorkStateCallback callback) {
        this.mWorkStateCallback = callback;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        initView(view, getContext());

        String sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();

        mAudioRecorder = new AudioRecorder(sdcardPath);
        mAudioPlayer = new AudioPlayer(sdcardPath, this);

        mAudioRecorder.setCallback(new AudioRecorder.Callback() {
            @Override
            public void onAudioRecorderError(int err) {
                if (mHandler != null) {
                    mHandler.sendEmptyMessage(1000 + err);
                }
            }

            @Override
            public void onAudioDataChanged(byte[] data, int len) {
                MainActivity mainActivity = (MainActivity) requireActivity();
                if (mainActivity.getWorkFragment().getVisualizerView() != null) {
                    mainActivity.getWorkFragment().getVisualizerView().updateVisualizer(data, len);
                }
            }
        });

        return view;
    }

    private void initView(View view, Context context) {
        Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
        //数据
        List<String> dataList = new ArrayList<String>();
        dataList.add("8000Hz 16bit 1channel");
        dataList.add("8000Hz 16bit 2channel");
        dataList.add("16000Hz 16bit 1channel");
        dataList.add("16000Hz 16bit 2channel");
        dataList.add("16000Hz 16bit 4channel");
        dataList.add("16000Hz 16bit 8channel");
        dataList.add("24000Hz 16bit 1channel");
        dataList.add("24000Hz 16bit 2channel");
        dataList.add("44100Hz 16bit 1channel");
        dataList.add("44100Hz 16bit 2channel");
        dataList.add("48000Hz 16bit 1channel");
        dataList.add("48000Hz 16bit 2channel");
        dataList.add("48000Hz 16bit 4channel");
        dataList.add("48000Hz 16bit 8channel");

        //适配器
        ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, dataList);
        //设置样式
        arrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner.setAdapter(arrAdapter);
        spinner.setOnItemSelectedListener(this);
        Button btnRecord = (Button) view.findViewById(R.id.btnRecord);
        btnRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startRecord();
            }
        });
        Button btnPlay = (Button) view.findViewById(R.id.btnPlay);
        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPlay();
            }
        });

        Spinner micTypeSpinner = view.findViewById(R.id.spinner_mic_type);
        List<String> micTypeList = new ArrayList<String>();
        micTypeList.add("DEFAULT");
        micTypeList.add("MIC");
        micTypeList.add("VOICE_UPLINK");
        micTypeList.add("VOICE_DOWNLINK");
        micTypeList.add("VOICE_CALL");
        micTypeList.add("VOICE_RECOGNITION");
        micTypeList.add("VOICE_COMMUNICATION");
        micTypeList.add("REMOTE_SUBMIX");
        micTypeList.add("UNPROCESSED");

        ArrayAdapter<String> micTypeArrAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, micTypeList);
        micTypeArrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        micTypeSpinner.setAdapter(micTypeArrAdapter);
        micTypeSpinner.setSelection(1);
        micTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String type = (String) adapterView.getAdapter().getItem(i);
                setAudioSource(type);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void setAudioSource(String type) {
        Logger.d(TAG, "setAudioSource: " + type);
        switch (type) {
            case "DEFAULT":
                mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
                break;
            case "VOICE_UPLINK":
                mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_UPLINK);
            case "VOICE_DOWNLINK":
                mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
                break;
            case "VOICE_CALL":
                mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
                break;
            case "VOICE_RECOGNITION":
                mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_RECOGNITION);
                break;
            case "VOICE_COMMUNICATION":
                mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
                break;
            case "REMOTE_SUBMIX":
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.REMOTE_SUBMIX);
                } else {
                    mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                }
                break;
            case "UNPROCESSED":
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.UNPROCESSED);
                } else {
                    mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                }
                break;
            case "MIC":
            default:
                mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                break;
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        String param = (String) parent.getAdapter().getItem(position);

        // 定义用于匹配数字的正则表达式模式
        final Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(param);

        // 使用ArrayList临时存储匹配到的数字
        ArrayList<Integer> numbersList = new ArrayList<>();

        // 查找所有匹配的数字并添加到列表中
        while (matcher.find()) {
            String numberStr = matcher.group();
            int number = Integer.parseInt(numberStr);
            numbersList.add(number);
        }

        // 将ArrayList转换为整数数组
        int[] numbers = new int[numbersList.size()];
        for (int i = 0; i < numbersList.size(); i++) {
            numbers[i] = numbersList.get(i);
        }

        create(numbers[0], numbers[1], numbers[2]);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    public void setSaveRecord(boolean isSave) {
        mIsSaveRecord = isSave;
    }

    private void startRecord() {
        mAudioRecording = true;
        mAudioRecorder.start(mIsSaveRecord);
        if (mWorkStateCallback != null) {
            mWorkStateCallback.onAudioRecord();
        }
    }

    private void startPlay() {
        mAudioPlaying = true;
        mAudioPlayer.start();
        if (mWorkStateCallback != null) {
            mWorkStateCallback.onAudioPlay();
        }
    }

    private void create(int s, int b, int c) {
        if (s > 0 && b > 0 && c > 0) {
            mAudioRecorder.initRecorder(s, c, b);
            mAudioPlayer.initPlayer(s, c, b);
        }
    }

    public void audioStop() {
        if (mAudioRecording) {
            mAudioRecording = false;
            mAudioRecorder.stop();
        }
        if (mAudioPlaying) {
            mAudioPlaying = false;
            mAudioPlayer.stop();
        }
    }

    @Override
    public void onPlayFinish() {
        if (mHandler != null) {
            mHandler.sendEmptyMessage(1);
        }
    }

    public void setHandler(Handler handler) {
        mHandler = handler;
    }
}
